package com.heima;

import io.mycat.config.model.rule.RuleAlgorithm;
import io.mycat.route.function.AbstractPartitionAlgorithm;
/**
 * 自定义多字段算法计算
 */
public class HeiMaBurstRuleAlgorithm extends AbstractPartitionAlgorithm implements RuleAlgorithm {

    // 单组数据容量
    Long volume;
    // 单组DN节点数量
    Integer step;
    // 分片模
    Integer mod;

    /**
     * 功能描述:
     * @param columVolume 3-2 1-2
     * @return: java.lang.Integer
     * @Author: zhangTao
     * @Date: 2020-04-20 2:01
     *
     * **分片ID =** **（dataId/volume）* step +分表ID/mod **
    */
    @Override
    public Integer calculate(String columVolume) {
        if (columVolume != null) {
            String[] temp = columVolume.split("-");
            if (temp.length == 2) {

                try {
                    Long dataId = Long.valueOf(temp[0]);
                    Long burstId = Long.valueOf(temp[2]);
                    int group = (int)(dataId / volume) * step;
                    int pos =  (group + (int) (burstId / mod));
                    System.out.println("mycat 规则为：【" +columVolume+"】-【"+ pos+"】");
                } catch (NumberFormatException e) {
                    System.out.println("mycat 规则报错信息为：【" +columVolume+"】-【"+ e.getMessage()+"】");
                }
            }
        }
        return 0;
    }

    @Override
    public Integer[] calculateRange(String beginValue, String endValue) {
        if (beginValue != null && endValue != null) {
            Integer begin = calculate(beginValue);
            Integer end = calculate(endValue);
            if (begin == null || end == null) {
                return new Integer[0];
            }
            if (end >= begin) {
                int len = end - begin + 1;
                Integer[] re = new Integer[len];
                for (int i = 0; i < len; i++) {
                    re[i] = begin + i;
                }
                return re;
            }
        }
        return new Integer[0];
    }
}
